package com.gs.synedocket.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;

import com.google.gson.reflect.TypeToken;
import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.callback.Callback;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.db.bean.SyncBean;
import com.gs.synedocket.db.sqlite.DBApi;
import com.gs.synedocket.util.DocketUtil;
import com.gs.synedocket.util.GsonUtil;
import com.gs.synedocket.util.NetworkUtil;
import com.gs.synedocket.util.OKHttpUtil;
import com.gs.synedocket.util.SPUtil;

import org.greenrobot.eventbus.EventBus;

public class GetVoidListService extends Service {

    private static boolean loop = true;
    private static Thread uploadThread;
    private final String SYNC_OBJ = "voidList";

    public static void stopThread() {
        loop = false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        loop = true;
        if (uploadThread == null) {
            uploadThread = new Thread(() -> {
                while (loop) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ignored) {
                    }
                    if (SPUtil.getInstance().getString(AllConstants.TOKEN).isEmpty()) break;
                    if (!NetworkUtil.getInstance().isConnected()) continue;
                    if (SPUtil.getInstance().getString(AllConstants.TRUCK_NAME).isEmpty()) continue;
                    getVoidList();
                }
            });
            uploadThread.start();
        }
        return START_STICKY;
    }

    private void getVoidList() {
        String query = DBApi.getInstance().getQueryCacheMap(AllConstants.VOID_LIST);
        if (TextUtils.isEmpty(query)) {
            query = getSyncBean();
            DBApi.getInstance().setQueryCacheMap(AllConstants.VOID_LIST, query);
        }
        OKHttpUtil.getInstance().postAsync(OKHttpUtil.NET_URL + "/api/syns", query,
                new Callback() {
                    @Override
                    public void onSuccess(Object obj) {
                        onGetDataSuccess((ApiResultData<String>) obj);
                    }

                    @Override
                    public void onFailed(Exception e) {
                    }
                }, new TypeToken<ApiResultData<String>>() {
                }.getType());
    }

    private void onGetDataSuccess(ApiResultData<String> result) {
        if (result.getStatus() != 2000) return;
        String data = result.getData();
        if (TextUtils.isEmpty(data)) {
            setQueryCache("");
            return;
        }
        boolean isSend = false;
        String[] split = data.split(",");
        for (String id : split) {
            DBApi.getInstance().updateDocketState(id, 6, 1);
            if (isSend) continue;
            // 判断当前操作的docket是否已作废
            String docketId = DocketUtil.getInstance().getDocketId();
            if (!TextUtils.isEmpty(docketId) && docketId.equals(id)) {
                isSend = true;
            }
        }
        setQueryCache(data);
        if (isSend) {
            sendBroadcast();
        }
    }

    private void setQueryCache(String ids) {
        String logQuery = DBApi.getInstance().getQueryCacheMap(AllConstants.VOID_LIST);
        SyncBean query = (SyncBean) GsonUtil.getInstance().fromJson(logQuery, SyncBean.class);
        query.setSynObjIds(ids);
        query.setOldTruckNo(query.getTruckNo());
        String json = GsonUtil.getInstance().toJson(query);
        DBApi.getInstance().setQueryCacheMap(AllConstants.VOID_LIST, json);
    }

    private String getSyncBean() {
        String truckNo = SPUtil.getInstance().getString(AllConstants.TRUCK_NAME);
        SyncBean bean = new SyncBean();
        bean.setSynObj(SYNC_OBJ);
        bean.setTruckNo(truckNo);
        bean.setOldTruckNo(truckNo);
        return GsonUtil.getInstance().toJson(bean);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    /**
     * 当前操作的docket已作废，发送广播通知
     */
    private void sendBroadcast() {
        EventBus.getDefault().post(new Event(EventCode.EVENT_VOID));
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (uploadThread != null) {
            uploadThread = null;
        }
        Log.i(AllConstants.TAG, "GetVoid onDestroy");
    }
}
